<template>
  <div>
    <ul>
      <li>
        <span>从</span>
        <el-date-picker v-model="queryParams.startTime" type="datetime" placeholder="开始时间"></el-date-picker>
      </li>
      <li>
        <span>到</span>
        <el-date-picker v-model="queryParams.endTime" type="datetime" placeholder="截止时间"></el-date-picker>
      </li>
      <li>
        <el-select
            v-model="queryParams.sort"
            placeholder="排序规则"
            clearable
        >
          <el-option
              v-for="item in sortOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          ></el-option>
        </el-select>
      </li>
      <li> <el-button @click="submitQuery">分段查询浇筑记录</el-button></li>
      <li>
        <el-button
            :disabled="!isDownloadable"
            type="primary"
            @click="downloadExcel"
        >
          下载工程量明细清单
        </el-button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
const props = defineProps({
  queryParams: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['queryData']);

// 深拷贝props中的queryParams，避免直接修改props
const queryParams = ref({...props.queryParams });

const FILE_SERVER_URL = `${import.meta.env.VITE_APP_API_BASE_URL}/apis`;

const sortOptions = ref([
  { value: 'true', label: '按桩基浇筑时间排序' },
  { value: 'false', label: '按桩号默认顺序排序' },
]);

// 计算属性：生成下载URL
const downloadUrl = computed(() => {

  const params = new URLSearchParams({
    pageNum: 1,
    pageSize: 492,
    startTime: queryParams.value.startTime || '',
    endTime: queryParams.value.endTime || '',
    sort: queryParams.value.sort || ''
  });



  return `${FILE_SERVER_URL}/pileData/createTableForPileQuantity?${params.toString()}`;
});

// 计算属性：检查下载按钮是否可用
const isDownloadable = computed(() => {
  return Boolean(queryParams.value.startTime && queryParams.value.endTime);
});

const submitQuery = () => {
  console.log('查询参数:', queryParams.value);

  // 简单验证
  if (!queryParams.value.startTime || !queryParams.value.endTime) {
    ElMessage.warning('请选择开始时间和截止时间');
    return;
  }

  emit('queryData', queryParams.value);
};

const downloadExcel = () => {
  // 验证参数
  if (!isDownloadable.value) {
    ElMessage.warning('请选择开始时间和截止时间');
    return;
  }

  // 方式一：直接打开链接
  //window.open(downloadUrl.value);


  // 方式二：使用fetch API(推荐，可处理错误)
  fetch(downloadUrl.value,{ method: 'GET' ,headers: { 'authorization':'Bearer '+localStorage.getItem('access_token')}})
    .then(response => {
      if (!response.ok) throw new Error('下载失败');
      return response.blob();
    })
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '工程量明细清单.xlsx';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    })
    .catch(error => {
      ElMessage.error('下载失败: ' + error.message);
    });
};

</script>

<style scoped>
ul {
  list-style-type: none;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

li {
  min-width: 200px;
}
</style>